package dlg.code.producer.s1;

import dlg.code.producer.ItemBuffer;

import java.util.concurrent.TimeUnit;

public class TakeThread implements Runnable{

    private final ItemBuffer itemBuffer;
    public TakeThread(ItemBuffer itemBuffer) {
        this.itemBuffer = itemBuffer;
    }

    @Override
    public void run() {
        while (true){
            synchronized (itemBuffer) {
                while (itemBuffer.isEmpty()) {
                    System.out.println(Thread.currentThread().getName() + " waiting");
                    try {
                        itemBuffer.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                String take = itemBuffer.take();
                System.out.println(Thread.currentThread().getName() + " take = " + take);
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                itemBuffer.notifyAll();
            }
        }
    }
}
